package com.zhong.thesimpleconnection.action;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.zhong.bmob.inter.IFileUpLoadUserDown;
import com.zhong.bmob.inter.IUpdate;
import com.zhong.bmob.model.User;
import com.zhong.bmob.server.FileUpLoad;
import com.zhong.bmob.server.Update;
import com.zhong.thesimpleconnection.R;
import com.zhong.thesimpleconnection.adapter.MyActivityListAdapter;
import com.zhong.thesimpleconnection.util.PermissionUtils;
import com.zhong.thesimpleconnection.view.MyDialogWarn;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.exception.BmobException;

public class MyActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener, IFileUpLoadUserDown, IUpdate {

    private TextView mLoginOrRegister;
    private LinearLayout mMyInfo;
    private ImageView mMyInfoIcon;
    private TextView mMyInfoName;
    private ImageView mToolbarSetting;
    private TextView mMyConversation;
    private TextView mMyContract;
    private TextView mJoin;
    private ListView mListView;
    private boolean hasMeasured;
    private int mHeight;
    private List<String> mMListItem;
    private File mImgFileSave;
    private User mUser;
    private MyDialogWarn mWarn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        init();
        setListener();
        setData();
    }

    private void setData() {
        mUser = (User) getIntent().getSerializableExtra("User");
        if (mUser != null) {
            SharedPreferences userShare = getSharedPreferences("User", MODE_PRIVATE);
            String state = userShare.getString("State", "");
            if (state.equals("已登录")) {
                mLoginOrRegister.setVisibility(View.GONE);
                mMyInfo.setVisibility(View.VISIBLE);
                mMyInfoName.setVisibility(View.VISIBLE);
                String imgPath = mUser.getImg();
                String realName = mUser.getRealName();
                if (realName != null && !"".equals(realName)){
                    mMyInfoName.setText(realName);
                }else {
                    String username = mUser.getUsername();
                    mMyInfoName.setText(username);
                }
                if (imgPath != null && !"".equals(imgPath)) {
                    Glide.with(MyActivity.this)
                            .load(imgPath)
                            .asBitmap()
                            .placeholder(R.drawable.ico_user_default)
                            .centerCrop()
                            .into(new BitmapImageViewTarget(mMyInfoIcon){
                                @Override
                                protected void setResource(Bitmap resource) {
                                    RoundedBitmapDrawable bitmap = RoundedBitmapDrawableFactory.create(getResources(), resource);
                                    bitmap.setCircular(true);
                                    mMyInfoIcon.setImageDrawable(bitmap);
                                }
                            });
                }
            }
        }
    }

    private void setListener() {
        mLoginOrRegister.setOnClickListener(this);
        mMyInfo.setOnClickListener(this);
        mMyInfoIcon.setOnClickListener(this);
        mMyInfoName.setOnClickListener(this);
        mMyConversation.setOnClickListener(this);
        mMyContract.setOnClickListener(this);
        mToolbarSetting.setOnClickListener(this);
        mJoin.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
    }

    private void init(){
        Toolbar toolbar = (Toolbar) findViewById(R.id.My_Toolbar);
        mToolbarSetting = (ImageView) findViewById(R.id.My_Toolbar_Setting);
        mMyInfo = (LinearLayout) findViewById(R.id.My_Info);
        mMyInfoIcon = (ImageView) findViewById(R.id.My_Info_UserIcon);
        mMyInfoName = (TextView) findViewById(R.id.My_Info_UserName);
        mLoginOrRegister = (TextView) findViewById(R.id.My_LoginOrRegister);
        mMyConversation = (TextView) findViewById(R.id.My_ConversationList);
        mMyContract = (TextView) findViewById(R.id.My_Contract);
        mJoin = (TextView) findViewById(R.id.My_FriendsAndGroup);
        mListView = (ListView) findViewById(R.id.My_List);
        setSupportActionBar(toolbar);
        ViewTreeObserver observer = mListView.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (hasMeasured == false){
                    mHeight = mListView.getHeight();
                    setListAdapter();
                    hasMeasured = true;
                }
                return true;
            }
        });
    }

    private void setListAdapter() {
        mMListItem = new ArrayList<>();
        String[] array = getResources().getStringArray(R.array.my_info_page);
        Collections.addAll(mMListItem, array);
        MyActivityListAdapter adapter = new MyActivityListAdapter(mMListItem, this, mHeight);
        mListView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                Toast.makeText(this, "0", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
                break;
            case 4:
                Toast.makeText(this, "4", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.My_Contract:
                break;
            case R.id.My_ConversationList:
                break;
            case R.id.My_FriendsAndGroup:
                break;
            case R.id.My_Info:
                break;
            case R.id.My_Info_UserIcon:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    PermissionUtils.requestPermission(this, PermissionUtils.CODE_CAMERA, mPermissionGrant);
                }else {
                    getMyImg();
                }
                break;
            case R.id.My_Info_UserName:
                break;
            case R.id.My_LoginOrRegister:
                break;
            case R.id.My_Toolbar_Setting:
                Toast.makeText(this, "Setting", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 120){
            if (resultCode == RESULT_OK){
                if (mImgFileSave != null) {
//                    BitmapFactory.Options options = new BitmapFactory.Options();
//                    options.inSampleSize = 2;
//                    options.inPreferredConfig = Bitmap.Config.RGB_565;
//                    options.inPurgeable = true;
//                    String path = mImgFileSave.getAbsolutePath();
//                    Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//                    mMyInfoIcon.setImageBitmap(bitmap);
                    Glide.with(MyActivity.this)
                            .load(mImgFileSave)
                            .asBitmap()
                            .placeholder(R.drawable.ico_user_default)
                            .centerCrop()
                            .into(new BitmapImageViewTarget(mMyInfoIcon){
                                @Override
                                protected void setResource(Bitmap resource) {
                                    RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                                    drawable.setCircular(true);
                                    mMyInfoIcon.setImageDrawable(drawable);
                                }
                            });
                    startWait(1);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            FileUpLoad.getFilePath(mImgFileSave, MyActivity.this);
                        }
                    }).start();
                }
            }
        }
    }

    private void getMyImg() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File info = new File(Environment.getExternalStorageDirectory(), "MyInfo");
        mImgFileSave = null;
        if (!info.exists()) {
            if (info.mkdir()) {
                File file = new File(info, "MyImg"+ SystemClock.currentThreadTimeMillis()+".jpg");
                if (!file.exists()) {
                    try {
                        if (file.createNewFile()) {
                            mImgFileSave = file;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    mImgFileSave = file;
                }
            }
        }else {
            File file = new File(info, "MyImg"+ SystemClock.currentThreadTimeMillis()+".jpg");
            if (!file.exists()) {
                try {
                    if (file.createNewFile()) {
                        mImgFileSave = file;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                mImgFileSave = file;
            }
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImgFileSave));
        startActivityForResult(intent, 120);
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant(){

        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_CAMERA:
                    getMyImg();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void upLoadSuccess(String fileUrl) {
        mUser.setImg(fileUrl);
        Update.UpdateBmob(mUser.getObjectId(), mUser, MyActivity.this);
    }

    @Override
    public void upLoadFail(BmobException exception) {
        int code = exception.getErrorCode();
        String message = exception.getMessage();
        Log.i("1234", message + "::" + code);
    }

    @Override
    public void UpdateSuccess() {
        stopWait();
    }

    @Override
    public void UpdateFailed() {

    }

    /**
     * 弹出的Dialog样式
     * @param type type = 1 表示弹出等待Dialog；type = 2、3和4 表示弹出警告Dialog
     */
    public void startWait(int type) {
        String title = null;
        String content = null;
        if (type == 1) {
            title = getStringFromResource(R.string.Dialog_FileUpload_Wait_Title);
        }
        int finalType = type;
        mWarn = new MyDialogWarn.Builder(this, R.style.MyDialog).
                setTitle(title)
                .setState(type)
                .setContent(content)
                .setCancelable(false)
                .setPositiveButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (finalType == 1) {

                        } else {
                            mWarn.dismiss();
                        }
                    }
                })
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (finalType == 1) {
                            mWarn.dismiss();
                        } else {
                            mWarn.dismiss();
                        }
                    }
                })
                .create();
        mWarn.show();
    }

    /**
     * 从资源文件中获取指定id所对应的值
     * @param id 资源文件中的id
     * @return 返回指定id所对应的值
     */
    private String getStringFromResource(int id){
        String ret;
        ret = this.getResources().getString(id);
        return ret;
    }

    /**
     * 取消dialog
     */
    private void stopWait(){
        mWarn.dismiss();
    }
}
